<template>
  <div>
    <!-- 右边基本表格 -->
    <BasicTable @register="registerTable">
      <!-- 表格标题 -->
      <template #tableTitle>
        <Icon :icon="getTitle.icon" class="m-1 pr-1" />
        <span> {{ title }} </span>
      </template>
      <!-- 表格右上角自定义按钮 -->
      <template #toolbar>
        <div v-for="(item, index) in butData" :key="index">
          <a-button :key="index" :type="item.color" @click="item.do" v-auth="item.auth">
            <Icon :icon="item.icon" /> {{ t(item.title) }}
          </a-button>
        </div>
      </template>
      <!-- 表格插槽 -->
      <template #prtqtyColumn="{ record }">
        <!-- input 输入框 -->
        <!-- <a-input-number
          :min="0"
          :max="100"
          :step="1"
          v-model:model-value="record.prtqty"
          :model-value="record.prtqty || 1"
          @update:model-value="(value) => handleChange(record, value)"
          style="width: 100%"
        /> -->
        <a-input v-model:value="record.prtqty" :min="1" :max="10" :step="1" />
      </template>
      <!-- 勾选 -->
      <template #checkBox="{ record, column }">
        <a-checkbox :checked="record[column.dataIndex] == '1' ? true : false" />
      </template>
    </BasicTable>
    <!-- <InputForm @register="registerDrawer" @success="handleSuccess" /> -->
    <BasicModal
      v-bind="$attrs"
      @register="registerModal"
      title="产品码补打"
      @ok="handleModal"
      :width="1000"
    >
      <BasicTable @register="registerPuArrTable" @row-click="handlePuArrRowClick" />
    </BasicModal>
    <PrintModal @register="registerPrintModal" />
  </div>
</template>
<script lang="ts">
export default defineComponent({
  name: 'ViewsPrintInvList',
});
</script>
<script lang="ts" setup>
import { defineComponent, watch, ref, onMounted } from 'vue';
import { useI18n } from '/@/hooks/web/useI18n';
import { useMessage } from '/@/hooks/web/useMessage';
import { router } from '/@/router';
import { Icon } from '/@/components/Icon';
import { BasicTable, useTable } from '/@/components/Table';
import { basInvDelete, updateFbStatus, savePic } from '/@/api/bas/inv/basInv';
import { listSet, customListData } from '/@/api/test/testData';
import { tabConfigData, schemasData } from '/@/utils/custom';
import { useDrawer } from '/@/components/Drawer';
import { BasicModal, useModal } from '/@/components/Modal';
import { BasicForm, FormSchema, useForm } from '/@/components/Form';
//import InputForm from './form.vue';
import PrintModal from '/@/components/print/printModal.vue';

const props = defineProps({
  treeCode: String,
  treeName: String,
});

const prtqty = ref<number>(1);

const { t } = useI18n('bas.inv.basInv');
const { showMessage } = useMessage();

//配置表单内容
const searchForm = ref<FormProps>({
  baseColProps: { lg: 6, md: 8 }, // 表单栅格布局
  labelWidth: 90, // 表单标签宽度
  showAdvancedButton: true,
  schemas: [],
  autoAdvancedLine: 4,
});

let tableColumns = ref<any>([]);
let butData = ref<any>([]);
let actionColumnData = ref<ActionItem[]>([]);
let layVoucherView = ref<any>({});
let listTabConfig = ref<any>({});
const getTitle = ref({
  // 表格标题图标
  icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
  value: listTabConfig.value.title,
});
let title = ref('');
let cinvcode = ref('');

const actionColumn: BasicColumn = {
  width: 120, //操作按钮宽度
  // actions: (record: Recordable) => {
  //   actionColumnData.value.forEach((item) => {
  //     if (item.title == '编辑') {
  //       item.onClick = () => handleForm({ cinvcode: record.cinvcode });
  //     }
  //     if (item.title == '删除') {
  //       item.popConfirm = {
  //         title: '是否确认删除数据',
  //         confirm: handleDelete.bind(this, { cinvcode: record.cinvcode }),
  //       };
  //     }
  //   });
  //   return actionColumnData.value;
  // },
  actions: (record: Recordable) => [
    {
      icon: 'clarity:timeline-line',
      title: t('详情配置'),
      onClick: handleDetails.bind(this, { cinvcode: record.cinvcode }),
      // auth: 'test:testData:edit',
    },
  ],
};

const tableColumnsPrint: BasicColumn[] = [
  {
    title: t('存货编码'),
    dataIndex: 'cinvcode',
    key: 'a.cinvcode',
    sorter: true,
    width: 130,
    align: 'left',
  },
  {
    title: t('存货名称'),
    dataIndex: 'cinvname',
    key: 'a.cinvname',
    sorter: true,
    width: 130,
    align: 'left',
  },
  {
    title: t('批次'),
    dataIndex: 'cbatch',
    key: 'a.cbatch',
    sorter: true,
    width: 100,
    align: 'center',
    editable: true,
    edit: true,
    editRow: true,
    editComponent: 'Input',
    editComponentProps: {
      maxlength: 50,
    },
    editRule: true,
  },
];

const [registerPuArrTable, invPrintTable] = useTable({
  columns: tableColumnsPrint,
  rowKey: 'id',
  pagination: false,
  bordered: true,
  
});

const [registerTable, { reload, setProps, getForm, getSelectRows }] = useTable({
  //actionColumn: actionColumn,
  columns: tableColumns,
  formConfig: searchForm.value as FormProps,
  rowSelection: {
    type: 'checkbox',
  },
  
});

const [registerModal, { openModal, closeModal }] = useModal();

onMounted(async () => {
  const res = await listSet({ viewCode: 'bas_inv_print_list' });
  title.value = res.layVoucherView.name;
  layVoucherView.value = res.layVoucherView;

  tableColumns.value = layVoucherView.value.flistTabCols; //表格表头

  searchForm.value.schemas = schemasData(layVoucherView.value.listQuery.queryCols);

  console.log('layVoucherView', layVoucherView.value);

  // 给表格里面的每一行的prtqty 值赋默认值为1
  tableColumns.value.forEach((item) => {
    if (item.dataIndex == 'prtqty') {
      item.editDefaultValue = 1;
    }
  });
  butData.value = layVoucherView.value.headBtns; //表格右上角按钮
  butData.value.forEach((item) => {
    if (item.btnKey == 'btnPrintInv') {
      item.do = () => handlePrintInv({});
    }
    if (item.btnKey == 'btnPrintInv2') {
      item.do = () => handlePrint({});
    }
    if (item.btnKey == 'btnBjPrint') {
      item.do = () => handlePrintBjPrint({});
    }
  });

  actionColumnData.value = layVoucherView.value.rowBtns; //表格行内按钮

  listTabConfig.value = tabConfigData(res.layVoucherView.listTabConfig);
  setProps({
    ...listTabConfig.value,
    api: customListData,
    beforeFetch: (params) => {
      for (const key in params) {
        if (Array.isArray(params[key])) {
          params[key + '_gte'] = params[key][0];
          params[key + '_lte'] = params[key][1];
          delete params[key];
        }
      }
      params.url = listTabConfig.value.api;
      return params;
    },
  });

  if (!listTabConfig.value.immediate) {
    reload();
  }
});

const [registerDrawer, { openDrawer }] = useDrawer();
const [registerPrintModal, { openModal: openPrintModal }] = useModal();

watch(
  () => props.treeCode,
  async () => {
    await getForm().setFieldsValue({
      clsCode: props.treeCode,
      'basInv.invCls.treeName': props.treeName,
    });
    reload();
  },
);

function handleDetails(record: Recordable) {
  cinvcode.value = record.cinvcode;
  // cversion.value = record.cversion;
  // title.value = `首页配置 （版本号：${record.cversion}）`;
  openAppsetDetailsDrawer(true);
}

function handleForm(record: Recordable) {
  openDrawer(true, record);
}

function handlePuArrRowClick(record: Recordable) {
  record.onEdit?.(true, false);
}

async function getInvList() {
  let invValid = true;
  let invList: Recordable[] = [];
  for (const record of invPrintTable.getDataSource()) {
    if (!(await record.onEdit?.(false, true))) {
      invValid = false;
    }
    invList.push({
      ...record,
      id: !!record.isNewRecord ? '' : record.id,
    });
  }
  for (const record of invPrintTable.getDelDataSource()) {
    if (!!record.isNewRecord) continue;
    invList.push({
      ...record,
      status: '1',
    });
  }
  if (!invValid) {
    throw { errorFields: [{ name: ['invList'] }] };
  }
  return invList;
}

async function handleDelete(record: Recordable) {
  const res = await basInvDelete(record);
  showMessage(res.message);
  handleSuccess();
}

// 补打：批次
async function handlePrint() {
  let arr = await getSelectRows();
  if (getSelectRows().length == 0) {
    showMessage(t('请先选择一行数据'));
    return;
  }
  await openModal(true, {});
  invPrintTable.setTableData(arr);
}

// 产品码补打
async function handleModal() {
  const data = await getInvList();
  let params = {
    ids: '',
    title: '产品码补打',
    height: '0.9',
    width: '0.9',
    fileName: '产品码补打',
  };
  params.ids = data.map((item) => `${item.cinvcode}-${item.cbatch}`).join(',');
  openPrintModal(true, params);
  closeModal();
  invPrintTable.setTableData([]);
}

// 产品码打印
async function handlePrintInv() {
  let arr = await getSelectRows();
  if (getSelectRows().length == 0) {
    showMessage(t('请先选择一行数据'));
    return;
  }
  console.log('arr', arr);
  const idsArr = arr.map((item) => {
    return item.invCode;
  });
  const prtqtys = arr.map((item) => {
    return item.invQty;
  });
  let params = {
    ids: idsArr.join(','),
    title: '产品码打印',
    height: '0.9',
    width: '0.9',
    fileName: '产品码打印',
    barSizeType: getForm().getFieldsValue().barSizeType,
    prtQtys: prtqtys.join(','),
  };
  console.log('params', params);
  // 查询条件
  // openPrintModal(true, params);
  await openModal(true, {});
}

// 标件产品打印
async function handlePrintBjPrint() {
  let arr = await getSelectRows();
  if (getSelectRows().length == 0) {
    showMessage(t('请先选择一行数据'));
    return;
  }
  
  const idsArr = arr.map((item) => {
    return item.cinvcode;
  });
  let params = {
    ids: idsArr.join(','),
    title: '标件产品打印',
    height: '0.9',
    width: '0.9',
    fileName: '标件产品打印',
  };
  openPrintModal(true, params);
}

function handleSuccess() {
  reload();
}
</script>
<style scoped>
:deep(.jeesite-editable-cell__action) {
  display: none;
}

/* .jeesite-editable-cell__action {
    display: none;
  } */

:deep(.edit-cell-align-center) {
  width: 100% !important;
}
</style>
